package server;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * TCPServer
 *
 * @author lx
 * @date 2024-06-07 21:08
 */
public class TCPServer {
    public static List<Socket> list = new ArrayList<>();

    public static void main(String[] args) throws Exception {
        ThreadPoolExecutor pool = new ThreadPoolExecutor(16, 16, 0, TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(8), Executors.defaultThreadFactory());

        ServerSocket ss = new ServerSocket(40001);
        System.out.println("开启成功,正在监听40001端口");
        while (true) {
            Socket accept = ss.accept();
            System.out.println(accept.getInetAddress().getHostAddress() + "上线了");
            list.add(accept);
            pool.execute(new HandleThread(accept));
        }
    }
}

class HandleThread extends Thread {
    public HandleThread(Socket socket) {
        this.socket = socket;
    }

    private Socket socket;

    @Override
    public void run() {
        byte[] buffer = new byte[1024];
        System.out.println("开启子线程");
        while (true) {
            try {
                InputStream is = socket.getInputStream();
                DataInputStream dis = new DataInputStream(is);
                int read = dis.read(buffer);
                String message = new String(buffer, 0, read, StandardCharsets.UTF_8);
                System.out.println("收到消息:" + message);
                System.out.println("read===" + read);
                if (read != 0) {
                    for (Socket socket1 : TCPServer.list) {
                        OutputStream os = socket1.getOutputStream();
                        DataOutputStream dos = new DataOutputStream(os);
                        dos.write(message.getBytes(StandardCharsets.UTF_8));
                        dos.flush();
                        JSONObject jsonObject = JSON.parseObject(message);
                        System.out.println(jsonObject.getInteger("type"));
                        System.out.println("发送消息成功");
                    }
                }

            } catch (Exception e) {
                System.out.println("有人掉线");
                e.printStackTrace();
                try {
                    socket.close();
                    TCPServer.list.remove(socket);
                    break;
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }
            }
        }
    }
}
